<template>
    <div class="message-button-group" style="user-select: none">
        <el-row class="message-button-group-inner">
            <el-button v-if="types.includes('text')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),textDialog=true">文本</el-button>
            <el-button v-if="types.includes('link')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),linkDialog=true">链接</el-button>
            <el-button v-if="types.includes('image')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),imageDialog=true">图片</el-button>
            <el-button v-if="types.includes('video')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),videoDialog=true">视频</el-button>
            <el-button v-if="types.includes('file')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),fileDialog=true">文件</el-button>
            <el-button v-if="types.includes('forward')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),forwardDialog = true">转发消息</el-button>
            <el-button v-if="types.includes('card')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="friendCardSubmit(1)">名片</el-button> 
            <el-button v-if="types.includes('card')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="friendCardSubmit(2)">公众号</el-button>
            <el-button v-if="types.includes('notice')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),noticeDialog=true">群公告</el-button>
            <el-button v-if="types.includes('document')" class="nav-button" type="primary" size="mini" icon="el-icon-plus" @click="reset(),documentDrawer = true">材料库</el-button>
            
        </el-row>

        <!-- 文本弹窗  -->
        <el-dialog :close-on-click-modal="false" :visible.sync="textDialog" width="400px" append-to-body>
            <div slot="title" style="display: flex; flex-direction: row;justify-content: space-between;">
                <span>添加文本</span>
            </div>
            <div class="edit-form" v-loading="textSubmitLoading">
                <rich-text-editor
                    autofocus
                    class="rich-text-editor"
                    placeholder="请输入快捷回复"
                    :withButton="false"
                    ref="editor"></rich-text-editor>
                <el-button @click="textSubmit" class="text-submit" type="primary">确定</el-button>
            </div>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" :visible.sync="noticeDialog" width="400px" append-to-body>
            <div slot="title" style="display: flex; flex-direction: row;justify-content: space-between;">
                <span>添加群公告</span>
            </div>
            <div class="edit-form" v-loading="noticeSubmitLoading">
                <rich-text-editor
                    autofocus
                    class="rich-text-editor"
                    placeholder="请输入快捷回复"
                    :withButton="false"
                    ref="editor"></rich-text-editor>
                <el-button @click="noticeSubmit" class="text-submit" type="primary">确定</el-button>
            </div>
        </el-dialog>
        <!-- 链接  -->
        <el-dialog :close-on-click-modal="false" :visible.sync="linkDialog" width="400px" append-to-body>
            <div slot="title" style="display: flex; flex-direction: row;justify-content: space-between;">
                <span>添加链接</span>
            </div>
            <el-form ref="form" label-width="0" v-loading="uploadimageloading">
                <el-form-item label="">
                    <el-input v-model="linkUrl" autofocus placeholder="请输入链接地址(必填)" /> 
                </el-form-item>
                <el-form-item label="">
                    <el-input v-model="linkTitle" placeholder="请输入标题(必填)" /> 
                </el-form-item>
                <el-form-item label="">
                    <div class="upload-wrap">
                        <div class="link-upload">
                            <uploadPictureCard :size="40" :src="uploadimage" @uploaded="linkUploaded" />
                        </div>
                        <el-input v-model="uploadimage" placeholder="请输入网络图地址" /> 
                    </div>
                </el-form-item>
                <el-form-item label="">
                    <el-input v-model="linkDesc" maxlength="200" show-word-limit rows="3" class="input-desc" resize="none" type="textarea" placeholder="请输入简介内容" /> 
                </el-form-item>
                <el-form-item label="">
                    <el-button class="link-submit" @click="linkSubmit" type="primary">确定</el-button>
                    <el-button class="link-submit" @click="linkDialog=false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>    
        <!-- 转发  -->
        <el-dialog :close-on-click-modal="false" :visible.sync="forwardDialog" width="400px" append-to-body>
            <div slot="title" style="display: flex; flex-direction: row;justify-content: space-between;">
                <span>添加转发</span>
            </div>
            <el-form ref="form" label-width="0" v-loading="uploadimageloading">
                <el-form-item label="">
                    <el-input v-model="forwardWxid" autofocus placeholder="请输入转发消息所在会话的WXID" /> 
                </el-form-item>
                <el-form-item label="">
                    <el-input v-model="forwardMsgId" placeholder="请输入消息ID" /> 
                </el-form-item>
                <el-form-item label="">
                    在链接后加入标识：&nbsp<el-switch v-model="addWxid" placeholder="请输入消息ID"></el-switch>
                </el-form-item>
                <el-form-item label="">
                    <el-button class="link-submit" @click="forwardSubmit" type="primary">确定</el-button>
                    <el-button class="link-submit" @click="forwardDialog=false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>   
        <!-- 图片  -->
        <el-dialog :close-on-click-modal="false" :visible.sync="imageDialog" width="400px" append-to-body>
            <div slot="title" style="display: flex; flex-direction: row;justify-content: space-between;">
                <span>添加图片</span>
            </div>
            <div class="upload-image">
                <uploadPictureCard :size="200" :src="imageSrc" @uploaded="imageUploaded" /> 
                <el-button class="image-submit" @click="imageSubmit" type="primary">确定</el-button>  
            </div>
        </el-dialog>    
        <!-- 视频  -->
        <el-dialog :close-on-click-modal="false" :visible.sync="videoDialog" width="400px" append-to-body>
            <div slot="title" style="display: flex; flex-direction: row;justify-content: space-between;">
                <span>添加视频</span>
            </div>
            <div class="upload-image">
                <uploadPictureCard :size="200" type="video" accept=".mp4, .ogg, .webm" :src="videoSrc" @uploaded="videoUploaded" /> 
                <el-button class="image-submit" @click="videoSubmit" type="primary">确定</el-button>  
            </div>
        </el-dialog>    
         <!-- 文件  -->
        <el-dialog :visible.sync="fileDialog" width="400px" append-to-body>
            <div slot="header" style="display: flex; flex-direction: row;justify-content: space-between;">
                <span>添加文件</span>
            </div>  
            <div class="upload-image" v-loading="imageSubmitLoading">
                <uploadFileCard :size="100" :file="file" @uploaded="fileUploaded" /> 
                <el-button class="image-submit" @click="fileSubmit" type="primary">确定</el-button>  
            </div>  
        </el-dialog>
        <!-- 名片 -->
        <dialogSelectFriend ref="dialogSelectFriend" />
        <!-- 材料库 -->
        <el-drawer
            class="document-dialog-drawer"
            title="材料库"
            :visible.sync="documentDrawer"
            :wrapperClosable="false"
            direction="rtl"
            :before-close="documentHandleClose">
            <div class="document-dialog-drawer-body" v-loading="documentFetching && documentPageNo == 0">
                <div class="document-list" v-infinite-scroll="documentInfiniteScroll" style="overflow:auto">
                    <div @click="selectDocument(document)" class="document-item infinite-list-item" v-for="(document) in documents" :key="document.id">
                        <div class="document-createtime">
                            {{ formatTime(document.createtime) }}
                            <i @click.stop="documentDelete(document)" class="el-icon-close document-item-close"></i>
                        </div>
                        <message-card :message="document" />
                        
                    </div>
                    <el-button @click="documentInfiniteScroll" type="text" :loading="documentFetching && documentPageNo !== 0">
                        {{ documentFetching && documentPageNo !== 0 ?'加载中':'点击加载更多' }}
                    </el-button>
                </div>
                
            </div>
        </el-drawer>    
    </div>
</template>
<script> 
import richTextEditor from '@/components/richTextEditor' 
import dialogSelectFriend from '@/components/dialog-select-friend'
import uploadPictureCard from '@/components/upload-picture-card'
import uploadFileCard from '@/components/upload-file-card'
import friend from '@/components/friend'
import pinyin from '@/lib/pinyin'
import emojiParse from '@/lib/wechat-emoji'
import messageCard from '@/components/message-card'
import { mapState } from 'vuex'
export default {
    name:'message-button-group',
    components:{ richTextEditor,uploadPictureCard,uploadFileCard,friend,messageCard,dialogSelectFriend },
    data(){
        return {
            textDialog:false,
            linkDialog:false,
            imageDialog:false,
            videoDialog:false,
            fileDialog:false,
            noticeDialog:false,
            forwardDialog:false,

            forwardWxid:"",
            forwardMsgId:"",
            addWxid:false,

            linkUrl:'',
            linkTitle:'',
            linkDesc:'',
            uploadimageloading:false,
            uploadimage:'',
            // ----------
            imageSrc:'',
            videoSrc:'',
            file:{},
            // ------- 材料库
            documentDrawer:false,
            documents:[],
            documentPageNo:0,
            documentPageSize:20,
            documentFetching:false,

            // submit loading
            textSubmitLoading:false,
            noticeSubmitLoading:false,
            // linkSubmitLoading:false,uploadimageloading,
            imageSubmitLoading:false,
            fileSubmitLoading:false,
            cardSbumitLoadding:false

        }
    },
    props:{
        csid:{
            type:Number,
            default:0
        },
        wxid:{
            type:String,
            default:""
        },
        types:{
            type:Array,
            default:()=>['text','image','video','link','file','card','document']
        }
    },
    mounted(){
    },
    watch:{
         
        documentDrawer(val,oldVal){
            if(val!==oldVal && val){
                this.documentPageNo = 0
                this.documents = []
                const params = { 
                    csid:this.csid,
                    pageNo:this.documentPageNo+1,pageSize:this.documentPageSize
                }
                this.getDocuments(params)    
            }
        },
        
        
    },
    computed:{
         
    },
    methods:{
        emojiParse,
        reset(){
            this.linkUrl='',
            this.linkTitle='',
            this.linkDesc='',
            this.uploadimageloading=false,
            this.uploadimage='',
            // ----------
            this.imageSrc='',
            this.file={},
            
            //转发
            this.forwardWxid="",
            this.forwardMsgId="",
            this.addWxid=false,

            // ------- 材料库
            this.documentDrawer=false,
            this.documents=[],
            this.documentPageNo=0,
            this.documentPageSize=20,
            this.documentFetching=false,

            // submit loading
            this.textSubmitLoading=false,
            // linkSubmitLoading:false,uploadimageloading,
            this.imageSubmitLoading=false,
            this.fileSubmitLoading=false,
            this.cardSbumitLoadding=false 
            
            this.$refs.editor&&this.$refs.editor.clear();
        },
        documentDelete(document){
            this.$confirm('是否删除该条材料?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteReply(document)   
            }).catch(() => {

            });
        },
        documentInfiniteScroll(e){
            const params = { 
                csid:this.csid,
                pageNo:this.documentPageNo+1,pageSize:this.documentPageSize
            }
            this.getDocuments(params) 
        },
         
        getDocuments(params){
             
            if(this.documentFetching || !params.csid )return;
            this.documentFetching = true;
            return this.$api.phrase.getlimit(params)
                .then((data)=>{
                    this.documentFetching = false
                    if(data && data[0]){
                        const replys = data.map(item=>{
                            try {
                                const rp = JSON.parse(item.msgextra)
                                rp.id = item.id
                                rp.createtime = item.createtime
                                return rp  
                            } catch (error) {
                                return {}   
                            }
                        }) 
                        if(params.pageNo === 1){
                            this.documents = replys
                        }else{
                            this.documents = this.documents.concat(replys)
                        }
                        this.documentPageNo = params.pageNo
                        this.documentPageSize = params.pageSize
                        
                    }
                }).catch(e=>{
                    this.documentFetching = false
                })
            },
            
        cardHandleClose(done){
            done()
        },
        documentHandleClose(done){
            done()
        },
        linkUploaded(src){
            this.uploadimage = this.config.apiUrl+src
        },
        imageUploaded(src){
            this.imageSrc =  src
        },
        videoUploaded(src){
            this.videoSrc =  src
        },
        fileUploaded(file){
            this.file = file
        },
        async imageChange(e){
            const target = e.target;
            const files = target.files;
            if(files.length){
                this.uploadimageloading = true
                const res = await this.upload(files[0])
                this.uploadimage = this.config.apiUrl+res
                target.value = ''
                this.uploadimageloading = false
            }
            
        },
        async upload(file){
            let res
            if (file.size / 1000 / 1000 > 100) {
                return console.log('由于微信限制，文件需要小于100M');
            }
            try {
                res = await this.uploadFile(file,{})
            } catch (error) {
                return  
            }
            return res
        },
        // edit
        async addPhrase(csid,message){
            return this.$api.phrase.add({
                csid, 
                msgtype:message.msgtype,msgcontent:'',
                msgextra:JSON.stringify(message)
            }) 
        },
        async deleteReply(reply) {
            return  this.$api.phrase.del(reply).then((data)=>{
                this.documents = this.documents.filter(r=>r.id!==reply.id)
            }).catch(e=>this.$msg(e))

        },
        // submit 
        async textSubmit(){
            const csid = this.csid;
            const content = this.$refs.editor.getEditorValue()||""
            if( !csid )return 
            if(content.trim()==''){
                return this.$message({
                    showClose: true,
                    message: '内容不能为空',
                    type: 'success'
                });
            }
            const message  = {
                msgtype:1,
                content:content.trim()
            }
            this.textSubmitLoading = true
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                    this.textDialog = false;
                }  
            } catch (error) { }
            this.textSubmitLoading = false
            
            
        },
        
        // submit 
        async noticeSubmit(){
            const csid = this.csid;
            const content = this.$refs.editor.getEditorValue()||""
            if( !csid )return 
            if(content.trim()==''){
                return this.$message({
                    showClose: true,
                    message: '内容不能为空',
                    type: 'success'
                });
            }
            const message  = {
                msgtype:15,
                content:content.trim()
            }
            this.noticeSubmitLoading = true
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                    this.noticeDialog = false;
                }  
            } catch (error) { }
            this.noticeSubmitLoading = false
            
            
        },
        async linkSubmit(){
            const csid = this.csid;
            if(!csid)return
            // linkUrl:'',
            // linkTitle:'',
            // linkDesc:'',
            // uploadimageloading:false,
            // uploadimage:'',

            
            const message = {
                msgtype:10,
                url: this.linkUrl,
                title: this.linkTitle,
                content: this.linkDesc,
                src: this.uploadimage 
            }
            if(message.url==''){
                return this.$message({
                    showClose: true,
                    message: '链接不能为空',
                    type: 'success'
                });
            }
            if(message.title==''){
                return this.$message({
                    showClose: true,
                    message: '标题不能为空',
                    type: 'success'
                });
            }
            this.uploadimageloading = true;
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                    this.linkDialog=false
                }  
            } catch (error) { }
            this.uploadimageloading = false
        },
        async forwardSubmit(){
            const csid = this.csid;
            if(!csid)return
            const message = {
                msgtype:16,
                forwardWxid: this.forwardWxid,
                forwardMsgId: this.forwardMsgId,
                addWxid:this.addWxid
            }
            if(message.forwardWxid==''){
                return this.$message({
                    showClose: true,
                    message: '转发消息所在会话的WXI不能为空',
                    type: 'success'
                });
            }
            if(message.forwardMsgId==''){
                return this.$message({
                    showClose: true,
                    message: '转发消息ID不能为空',
                    type: 'success'
                });
            }
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                    this.forwardDialog=false
                }  
            } catch (error) { }
        },
        async imageSubmit(){
            const csid = this.csid;
            if(!csid )return
            const message = {
                msgtype:2,
                src: this.imageSrc,
            }
            if(message.src==''){
                return this.$message({
                    showClose: true,
                    message: '请上传图片',
                    type: 'success'
                });
            }
            this.imageSubmitLoading = true;
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                    this.imageDialog=false
                }  
            } catch (error) { }
            this.imageSubmitLoading = false    
        },
        async videoSubmit(){
            const csid = this.csid;
            if(!csid )return
            const message = {
                msgtype:4,
                src: this.videoSrc,
            }
            if(message.src==''){
                return this.$message({
                    showClose: true,
                    message: '请上传视频',
                    type: 'success'
                });
            }
            this.imageSubmitLoading = true;
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                    this.videoDialog=false
                }  
            } catch (error) { }
            this.imageSubmitLoading = false    
        },
        async fileSubmit(){
            const csid = this.csid;
            if(!csid)return
            const message = {
                msgtype:6,
                src: this.file.src,
                title:this.file.name,
                content:this.file.src
            }
            if(message.src==''){
                return this.$message({
                    showClose: true,
                    message: '请添加文件',
                    type: 'success'
                });
            }
            this.fileSubmitLoading = true;
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                    this.fileDialog = false
                }  
            } catch (error) { }
            this.fileSubmitLoading = false    
        },
        async friendCardSubmit(type){
            const csid = this.csid;
            const wxid = this.wxid;

            if(!csid || !wxid)return

            const selectFriends = await this.$refs.dialogSelectFriend.getSelectFriendsAsync({
                csid,
                wxaccount:wxid,
                multiple:false,
                filterType:type,
                type:0 
            })

            if(!selectFriends){
                return 
            }
            const friendChecked = selectFriends[0];
            const message = {
                msgtype:13,
                src: friendChecked.avatar,
                title:friendChecked.friendnick,
                wxid:friendChecked.friendwxid,
                alias:friendChecked.friendalias,
                certflag: (friendChecked.isbrand||friendChecked.isent)?24:0
            }  
            try {
                const res = await this.addPhrase(csid,message) 
                if(res){
                    this.onCreate(message)
                }  
            } catch (error) { }

        },
        selectDocument(document){
            this.onCreate(document)
            this.documentDrawer = false
        },

        onCreate(message){
            this.$emit('create',message)
            this.reset()
        }

        
    }    
}
</script>
<style scoped>
.message-button-group >>> div.el-card__body{
    padding: 20px!important;
}
.message-button-group >>> div.el-card__header{
    padding: 18px 20px;
}

.nav-button{
    padding:5px;
    margin: 10px 0 0 10px;
}
.el-row{
     
}
.message-button-group-inner{
    margin-top:-10px;
    margin-left: -10px;
}
.el-row:last-child{
}
.edit-form{
}
.rich-text-editor{
    height: 150px;
    border-radius: 3px;
    z-index: 1;
}
.text-submit{
    margin-top: 10px;
    width: 100%;
}
.upload-wrap{
    display: flex;
    
}
.link-upload{
    margin-right: 10px;
    width: 40px;
    height: 40px;
    flex-shrink: 0;
}
.upload-picture-card{
    width: 100%;
    height: 100%;
    position: relative;
}
.el-upload{
    border: 1px dashed #c0ccda;
    border-radius: 3px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    vertical-align: top; 
    position: relative;
    z-index: 1;
    opacity: 0;  
}
.upload-picture-card .el-upload .el-icon-plus{
    display:none
}
.upload-picture-card .el-upload:hover,
.upload-picture-card .empty{
    border-color: #409EFF;
    color: #409EFF;
    background: rgba(255,255,255,.7);
    opacity: 1;
}
.upload-picture-card .empty .el-icon-edit{
    display: none
}
.upload-picture-card .empty .el-icon-plus{
    display: inline-block;
}
.upload-picture-input{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
}
.upload-picture-thumb{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit:cover;
    border-radius: 3px;
    opacity: 1;
}
.input-desc >>> textarea{
    padding:10px;
}
.input-desc >>> .el-input__count{
    line-height:14px;
    background:transparent
}
.upload-image{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.image-submit{
    margin-top: 20px;
}
.friend-list{
    padding: 10px;
    margin: 0
}
.friend-list-inner{
    margin-left: -10px;
    margin-top: -10px;
}

.friend-item{
    position: relative;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 3px;
    box-sizing: border-box;
    padding: 10px 10px 10px 10px;
}
.friend-item-grid{
    float: left;
    width: 50%;
    padding-left: 10px;
    padding-top: 10px;
    box-sizing: border-box;
}
.friend-item-status-label {
    position: absolute;
    right: -17px;
    top: -7px;
    width: 46px;
    height: 26px;
    background: #13ce66;
    text-align: center;
    transform: rotate(45deg);
    box-shadow: 0 1px 1px #ccc;
    display: none
}
.friend-item-check-success{
    color: #fff;
    font-size: 12px;
    margin-top: 12px;
    transform: rotate(-45deg);
}
.is-success .friend-item-status-label{
    display: block
}
 
.card-dialog-drawer >>> .el-drawer__body {
    height:100%;
} 
.card-dialog-drawer-body{
    height:100%;
    display: flex;
    flex-direction: column;
}
.card-dialog-drawer-scroll{
    height: 100%;
    overflow: auto;
    background: #fafafa;
}
.card-dialog-drawer-filter{
    padding:0 10px 10px;
    border-bottom: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.card-dialog-drawer-filter .el-radio-group{
    margin-bottom: 10px;
}
.card-dialog-drawer-footer{
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    padding: 10px;
    border-top: 1px solid #ccc;
}

/* ----- */
.document-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}
.document-item-close{
    font-size: 16px;
    vertical-align: text-top;
}
.document-item-close:hover{
    color: #50bfff
}
.document-item:hover{
    transform: translate(-5px,0);
}
.document-createtime{
    color: #999;
    font-size: 12px;
    text-align: right;
}
.document-text{
    color: #333;
    font-size: 16px;
    word-break: break-all;
    
}
.document-image{
    width: 100px;
    height: 100px;
    background-color: #f1f1f1;
}
.document-image-slot{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 14px;
}
.document-list{
    padding: 10px;
}
.document-dialog-drawer >>> .el-drawer__body {
    height:100%;
}  
.document-dialog-drawer >>> .el-drawer__header{
    margin-bottom: 20px;
}
.document-dialog-drawer-body{
    height:100%; 
    display: flex;
    flex-direction: column; 
    background: #f1f1f1;
    border-top: 1px solid #ccc;
}
.document-list .el-button{
    width: 100%
}
</style>